<template>
  <div class="upload-page-wrap">
    <div class="upload-section card-style">
      <div class="upload-title">
        <svg class="custom-upload-svg" viewBox="0 0 48 48" width="30" height="30">
          <defs>
            <linearGradient id="upload-gradient" x1="0" y1="0" x2="1" y2="1">
              <stop offset="0%" stop-color="#53caff"/>
              <stop offset="100%" stop-color="#409eff"/>
            </linearGradient>
          </defs>
          <path d="M24 6v24M24 6l-8 8M24 6l8 8" stroke="url(#upload-gradient)" stroke-width="4" fill="none" stroke-linecap="round" stroke-linejoin="round"/>
          <rect x="8" y="32" width="32" height="10" rx="6" fill="#e9f0fb" stroke="#b3c6e8" stroke-width="2.5"/>
        </svg>
        <span>文件上传</span>
      </div>
      <el-dropdown trigger="click" @command="handleTypeSelect">
        <div class="pretty-upload-inner pretty-upload-dropdown-trigger custom-upload-trigger upload-choose-btn mini-upload-btn">
          <svg class="custom-upload-svg-large" viewBox="0 0 48 48" width="44" height="44">
            <defs>
              <linearGradient id="upload-gradient2" x1="0" y1="0" x2="1" y2="1">
                <stop offset="0%" stop-color="#53caff"/>
                <stop offset="100%" stop-color="#409eff"/>
              </linearGradient>
            </defs>
            <circle cx="24" cy="24" r="22" fill="#f8fafc" stroke="#b3c6e8" stroke-width="2.5"/>
            <path d="M24 12v16M24 12l-7 7M24 12l7 7" stroke="url(#upload-gradient2)" stroke-width="4" fill="none" stroke-linecap="round" stroke-linejoin="round"/>
            <rect x="13" y="32" width="22" height="6" rx="3" fill="#e9f0fb" stroke="#b3c6e8" stroke-width="2"/>
          </svg>
          <div class="pretty-upload-text">
            <span class="pretty-upload-main">
              <span class="pretty-upload-link">选择上传类型</span>
            </span>
            <span class="pretty-upload-tip"></span>
          </div>
        </div>
        <el-dropdown-menu slot="dropdown" class="custom-dropdown-menu">
          <el-dropdown-item command="fofa">
            <i class="el-icon-upload"></i> fofa
          </el-dropdown-item>
          <el-dropdown-item command="zoomeye">
            <i class="el-icon-upload"></i> zoomeye
          </el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
      <input
        v-if="showUpload"
        ref="fileInput"
        type="file"
        :multiple="true"
        style="display:none"
        @change="handleFileInputChange"
        accept=".csv,.json"
      />
      <!-- 文件列表和进度条 -->
      <div v-if="fileList.length" class="upload-file-list mini-upload-file-list">
        <div v-for="file in fileList" :key="file.uid" class="upload-file-item custom-upload-file-item mini-upload-file-item">
          <span class="file-name">
            <i class="el-icon-document" style="color:#409eff;margin-right:6px;font-size:16px;"></i>
            {{ file.name }}
          </span>
          <el-progress
            :percentage="progressMap[file.uid] || 0"
            :status="(progressMap[file.uid] === 100) ? 'success' : undefined"
            :stroke-width="6"
            class="upload-progress custom-upload-progress mini-upload-progress"
            :text-inside="false"
            color="#53caff"
          ></el-progress>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  name: "UploadFileWithProgress",
  data() {
    return {
      uploadHeaders: {
        Authorization: 'Bearer ' + (localStorage.getItem('token') || '')
      },
      fileList: [],
      progressMap: {},
      uploadType: "",
      showUpload: false
    };
  },
  methods: {
    handleTypeSelect(type) {
      this.uploadType = type;
      this.fileList = [];
      this.progressMap = {};
      this.showUpload = false;
      // 选择类型后显示input[type=file]并自动弹出文件选择框
      this.$nextTick(() => {
        this.showUpload = true;
        this.$nextTick(() => {
          if (this.$refs.fileInput) {
            this.$refs.fileInput.value = null;
            this.$refs.fileInput.click();
          }
        });
      });
    },
    handleFileInputChange(e) {
      const files = Array.from(e.target.files);
      // 生成带uid的fileList
      this.fileList = [];
      files.forEach((file, idx) => {
        const ext = file.name.split('.').pop().toLowerCase();
        if (
          (this.uploadType === "fofa" || this.uploadType === "zoomeye") &&
          (ext === "csv" || ext === "json")
        ) {
          file.uid = Date.now() + '-' + idx;
          this.fileList.push(file);
          this.$set(this.progressMap, file.uid, 0);
          this.uploadSingleFile(file);
        } else {
          this.$message.error('文件类型不合法，只允许上传csv或json文件');
        }
      });
    },
    uploadSingleFile(file) {
      let url = "";
      if (this.uploadType === "fofa") {
        if (file.name.toLowerCase().endsWith('.csv')) {
          url = "http://192.168.124.9:8888/fofa/uploadCsv";
        } else if (file.name.toLowerCase().endsWith('.json')) {
          url = "http://192.168.124.9:8888/fofa/uploadJson";
        }
      } else if (this.uploadType === "zoomeye") {
        if (file.name.toLowerCase().endsWith('.csv')) {
          url = "http://192.168.124.9:8888/zoomeye/uploadCsv";
        } else if (file.name.toLowerCase().endsWith('.json')) {
          url = "http://192.168.124.9:8888/zoomeye/uploadJson";
        }
      }
      if (!url) {
        this.$message.error('请选择正确的上传类型，并上传csv或json文件');
        this.progressMap[file.uid] = 0;
        return;
      }
      const formData = new FormData();
      formData.append("file", file);
      axios.post(url, formData, {
        headers: {
          ...this.uploadHeaders,
          "Content-Type": "multipart/form-data"
        },
        onUploadProgress: (event) => {
          if (event && event.total > 0) {
            const percent = Math.round((event.loaded / event.total) * 100);
            this.$set(this.progressMap, file.uid, percent);
          }
        }
      })
      .then((res) => {
        // 判断后端返回的code
        if (res && res.data && res.data.code === 1) {
          this.$message.error(`${file.name} 上传失败，请检查文件格式或内容`);
          this.$set(this.progressMap, file.uid, 0);
        } else {
          this.$message.success(`${file.name} 上传成功`);
          this.$set(this.progressMap, file.uid, 100);
        }
      })
      .catch(() => {
        this.$message.error(`${file.name} 上传失败`);
        this.$set(this.progressMap, file.uid, 0);
      });
    }
  }
};
</script>

<style scoped>
.upload-page-wrap {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  margin: 48px auto;
  max-width: 900px;
}

.card-style {
  background: rgba(255, 255, 255, 0.85);
  backdrop-filter: blur(14px);
  border-radius: 28px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.10);
  padding: 48px 38px;
  display: flex;
  flex-direction: column;
  align-items: center;
  transition: all 0.3s;
  min-width: 340px;
  max-width: 420px;
}
.card-style:hover {
  transform: translateY(-6px);
  box-shadow: 0 12px 36px rgba(0, 0, 0, 0.16);
}

.upload-title {
  font-size: 28px;
  font-weight: 700;
  color: #1f4fff;
  margin-bottom: 36px;
  display: flex;
  align-items: center;
  gap: 16px;
}

.custom-upload-svg {
  font-size: 32px;
}

.pretty-upload-dropdown-trigger {
  cursor: pointer;
  border-radius: 18px;
  border: 2.5px dashed #1f4fff;
  background: linear-gradient(to bottom right, #f3f8ff, #ffffff);
  padding: 38px 0 28px 0;
  margin-bottom: 28px;
  box-shadow: inset 0 0 12px rgba(0, 31, 79, 255, 0.10);
  transition: all 0.3s;
  display: flex;
  flex-direction: column;
  align-items: center;
  min-width: 260px;
  max-width: 380px;
}
.pretty-upload-dropdown-trigger:hover {
  background: #e8f1ff;
  border-color: #2a62ff;
}

.custom-upload-svg-large {
  font-size: 44px;
  color: #2a62ff;
  margin-bottom: 18px;
}

.pretty-upload-main {
  font-size: 20px;
  font-weight: 700;
  color: #2a62ff;
  margin-bottom: 10px;
}

.pretty-upload-link {
  font-size: 18px;
  color: #1f4fff;
  text-decoration: underline;
  font-weight: 600;
}

.pretty-upload-tip {
  font-size: 15px;
  color: #6c8fff;
  margin-top: 8px;
}

</style>
